package com.igeek.collateral.utils;

import com.deepoove.poi.XWPFTemplate;
import com.igeek.collateral.entity.Contract;
import org.springframework.util.ResourceUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * 合同word文件生成工具类
 *
 * @author ding
 * @since 2024/6/2
 */
public class WordUtils{

    public static String createWord(Contract contract) throws IOException{
        File file = ResourceUtils.getFile("classpath:template/项目合作协议书.docx");
        String outPath = ".\\files\\" + contract.getContractName() + ".docx";

        Map<String,Object> map = new HashMap<>();
        map.put("partyA",contract.getPartyA());
        map.put("partyB",contract.getPartyB());
        map.put("amount",contract.getAmount());
        map.put("servicePeriod",contract.getServicePeriod());

        try (
            XWPFTemplate template = XWPFTemplate.compile(file).render(map);
            FileOutputStream fos = new FileOutputStream(outPath);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ){
            template.write(bos);
            byte[] bytes = bos.toByteArray();
            bos.flush();

            //template.writeAndClose(Files.newOutputStream(Paths.get(outPath)));
            template.write(fos);
            fos.flush();

            String filePath = outPath.substring(0,outPath.lastIndexOf(".")) + ".pdf";
            Doc2PdfUtil.doc2pdf(bytes,filePath);

            return filePath;
        }
    }

}
